exports.__esModule = true;

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

exports.default = class extends think.Service {
    constructor() {
        super();
        const db = this.db;
        this.userModel = db['sys_user'];
        this.roleUserModel = db['sys_role_user'];
        this.roleModel = db['sys_role'];
        this.roleMenuModel = db['sys_role_menu'];
        this.menuModel = db['sys_menu'];
        this.defData = {
            userid: '000000',
            roleid: '000000'
        };
        this.userModel.hasMany(this.roleUserModel, { foreignKey: 'userid', targetKey: 'id' });
    }

    /**
     * 获取部门列表
     * @param {*} data 
     */
    getOrgByRole(data) {
        var _this = this;

        return _asyncToGenerator(function* () {
            const Op = _this.db.Sequelize.Op;
            try {
                return yield _this.db['sys_org'].findAll({
                    where: {
                        id: {
                            [Op.in]: data.orgids
                        }
                    },
                    attributes: ['id', 'org_name', 'org_code']
                });
            } catch (err) {
                return _this.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 查询角色列表
     */
    getRoleList(data) {
        var _this2 = this;

        return _asyncToGenerator(function* () {
            const Op = _this2.db.Sequelize.Op;
            data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            let where = { id: { [Op.not]: _this2.defData.roleid } };
            if (data.rolename) {
                where.rolename = {
                    [Op.like]: '%' + data.rolename + '%'
                };
            }
            try {
                return yield _this2.roleModel.findAndCountAll({
                    where: where,
                    limit: parseInt(data.pageSize),
                    offset: parseInt(data.start)
                });
            } catch (err) {
                return _this2.exceptionService.handleError(err);
            }
        })();
    }

    /**
     * 删除角色信息
     * @data1 Object
     * data1.id --角色id String
     * @data2 Object
     * data2.update_date --更新时间 datetime
     * data2.update_by --更新人 String
     */
    delSysRoleInfo(data1) {
        var _this3 = this;

        return _asyncToGenerator(function* () {
            const where = { id: data1.id };
            // const where2 = {roleid:data1.id};
            try {
                if (data1.id === _this3.defData.roleid) {
                    return { msg: '系统角色不能删除' };
                } else {
                    return yield _this3.roleModel.destroy({ where: where });
                    // const roleUserCount = await this.roleUserModel.count({where:where2});
                    // if(roleUserCount>0){
                    //     return {msg:'所选角色已绑定用户，请先删除对应用户信息'};
                    // }else{
                    //     const delRole = await this.roleModel.update(data2,{where:where});
                    //     if(delRole){
                    //         return true;
                    //     }else{
                    //         return {msg:"角色信息删除错误"};
                    //     }
                    // }
                }
            } catch (err) {
                return _this3.exceptionService.handleError(err);
            }
        })();
    }

    /**
     * 保存角色信息
     * data --保存字段
     * oldList -- 原部门数组
     * newList --新部门数组
     */
    saveRoleInfo(data, oldList, newList) {
        var _this4 = this;

        return _asyncToGenerator(function* () {
            const Op = _this4.db.Sequelize.Op;
            try {
                const oldRole = yield _this4.roleModel.findOne({
                    where: { [Op.or]: { rolename: data.rolename, rolecode: data.rolecode } },
                    attributes: ['id']
                });
                if (data.id) {
                    if (oldRole && oldRole.id !== data.id) {
                        return false;
                    } else {
                        return yield _this4.roleModel.update(data, { where: { id: data.id } });
                    }
                } else {
                    if (oldRole) {
                        return false;
                    } else {
                        data.id = think.uuid('v1');
                        return yield _this4.roleModel.create(data);
                    }
                }
            } catch (err) {
                return _this4.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 查询角色名称列表
     */
    getRoleNames() {
        var _this5 = this;

        return _asyncToGenerator(function* () {
            const Op = _this5.db.Sequelize.Op;
            try {
                return yield _this5.roleModel.findAll({ where: { id: { [Op.not]: _this5.defData.roleid } } });
            } catch (err) {
                return _this5.exceptionService.handleError(err);
            }
        })();
    }

    /*****************角色用户相关 begin*****************/

    /**
     * 根据用户id获取角色列表
     * @data
     * data.userid --用户id
     * 
     * @return
     * 
     */
    getRoleByUser(data) {
        var _this6 = this;

        return _asyncToGenerator(function* () {
            const where = {
                userid: data.userid
            };
            try {
                return yield _this6.roleUserModel.findAll({ where: where, attributes: [['roleid', 'id']] });
            } catch (err) {
                return _this6.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 删除当前用户与当前角色绑定关系
     */
    delUserRole(data) {
        var _this7 = this;

        return _asyncToGenerator(function* () {
            try {
                return yield _this7.roleUserModel.destroy({ where: data });
            } catch (err) {
                return _this7.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 按角色分页查询用户列表
     */
    getUsersByRole(data) {
        var _this8 = this;

        return _asyncToGenerator(function* () {
            data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            const optJson = JSON.parse(data.options);
            const Op = _this8.db.Sequelize.Op;
            let where = {
                del_flag: 0,
                id: {
                    [Op.not]: _this8.defData.userid //不显示系统用户
                }
            };
            if (optJson.username) {
                where.username = {
                    [Op.like]: '%' + optJson.username + '%'
                };
            }
            if (optJson.realname) {
                where.realname = {
                    [Op.like]: '%' + optJson.realname + '%'
                };
            }
            try {
                const userIds = yield _this8.userModel.findAndCountAll({
                    where: where,
                    limit: parseInt(data.pageSize),
                    offset: parseInt(data.start),
                    include: [{ model: _this8.roleUserModel, where: { roleid: data.roleid } }]
                });
                return userIds;
            } catch (err) {
                return _this8.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 未绑定当前角色的用户列表分页查询
     */
    getUsersNotBindRole(data) {
        var _this9 = this;

        return _asyncToGenerator(function* () {
            let where = { del_flag: 0 };
            let userids = [];
            const optJson = JSON.parse(data.options);
            const Op = _this9.db.Sequelize.Op;
            data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            if (optJson.username) {
                where.username = {
                    [Op.like]: '%' + optJson.username + '%'

                };
            }
            if (optJson.realname) {
                where.realname = {
                    [Op.like]: '%' + optJson.realname + '%'
                };
            }

            try {
                const list = yield _this9.roleUserModel.findAll({
                    where: { roleid: data.roleid },
                    attributes: ['userid']
                });
                userids = list.map(function (item) {
                    return item.userid;
                });
                userids.push(_this9.defData.userid);
                where.id = { [Op.notIn]: userids };
                const list2 = yield _this9.userModel.findAndCountAll({
                    where: where,
                    limit: parseInt(data.pageSize),
                    offset: parseInt(data.start)
                });
                return list2;
            } catch (err) {
                return _this9.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 保存用户角色绑定
     */
    saveUserRole(data) {
        var _this10 = this;

        return _asyncToGenerator(function* () {
            const upData = data.userList.map(function (item) {
                const param = {
                    id: think.uuid('v1'),
                    roleid: data.roleid,
                    userid: item
                };
                return param;
            });
            try {
                return yield _this10.roleUserModel.bulkCreate(upData);
            } catch (err) {
                return _this10.exceptionService.handleError(err);
            }
        })();
    }

    /************角色菜单 begin*********** */

    /**
     * 根据角色获取菜单权限
     */
    getRoleMenu(data) {
        var _this11 = this;

        return _asyncToGenerator(function* () {
            try {
                return yield _this11.roleMenuModel.findAll({
                    where: data,
                    attributes: [['menuid', 'id']]
                });
            } catch (err) {
                return _this11.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 保存角色菜单权限关联记录
     */
    saveRoleMenu(data) {
        var _this12 = this;

        return _asyncToGenerator(function* () {
            const Op = _this12.db.Sequelize.Op;
            try {
                if (data.delList.length > 0) {
                    const del = yield _this12.roleMenuModel.destroy({
                        where: {
                            roleid: data.roleid,
                            menuid: {
                                [Op.in]: data.delList
                            }
                        }
                    });
                }
                if (data.addList.length > 0) {
                    data.addList = data.addList.map(function (item) {
                        const params = {
                            id: think.uuid('v1'),
                            roleid: data.roleid,
                            menuid: item
                        };
                        return params;
                    });
                    yield _this12.roleMenuModel.bulkCreate(data.addList);
                }
                return true;
            } catch (err) {
                return _this12.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 按分配角色获取所有菜单项
     * @data --Array 角色id数组
     * @return --Array 菜单列表
     * 
     */

    getUserRoleMenu(data) {
        var _this13 = this;

        return _asyncToGenerator(function* () {
            const roleList = data;
            const Op = _this13.db.Sequelize.Op;
            let arr = [];
            let list = [];
            try {
                const menuIds = yield _this13.roleMenuModel.findAll({
                    where: {
                        roleid: {
                            [Op.in]: roleList
                        }
                    },
                    attributes: ['menuid']
                });
                if (menuIds.length > 0) {
                    for (var i = 0; i < menuIds.length; i++) {
                        arr.push(menuIds[i].menuid);
                    }
                    let childs = yield _this13.menuModel.findAll({
                        where: {
                            id: {
                                [Op.in]: arr
                            },
                            menu_source: 1,
                            is_show: 1
                        },
                        attributes: ['id']
                    });
                    if (childs.length > 0) {
                        childs = childs.map(function (m) {
                            return m.id;
                        });
                        const allIds = yield _this13.getParent(childs);
                        if (!allIds.error) {
                            const allMenu = yield _this13.menuModel.findAll({
                                where: {
                                    id: {
                                        [Op.in]: allIds
                                    },
                                    menu_source: 1,
                                    is_show: 1
                                },
                                order: [['menu_order']]
                            });
                            list = allMenu;
                        }
                    }
                }
                return list;
            } catch (err) {
                return _this13.exceptionService.handleError(err);
            }
        })();
    }

    /**
     * 向父级递归查询所有菜单id
     */
    getParent(idArr) {
        var _this14 = this;

        return _asyncToGenerator(function* () {
            let arr = idArr;
            const Op = _this14.db.Sequelize.Op;
            const getList = (() => {
                var _ref = _asyncToGenerator(function* (childArr) {
                    const where = {
                        id: {
                            [Op.in]: childArr
                        },
                        parent_id: {
                            [Op.notIn]: childArr
                        }
                    };
                    try {
                        const parentids = yield _this14.menuModel.findAll({
                            where: where,
                            attributes: ['parent_id']
                        });
                        if (parentids && parentids.length > 0) {
                            let parentid = [];
                            for (let i = 0; i < parentids.length; i++) {
                                arr.push(parentids[i].parent_id);
                                parentid.push(parentids[i].parent_id);
                            }
                            return yield getList(parentid);
                        } else {
                            return arr;
                        }
                    } catch (err) {
                        return _this14.exceptionService.handleError(err);
                    }
                });

                return function getList(_x) {
                    return _ref.apply(this, arguments);
                };
            })();
            return yield getList(idArr);
        })();
    }

    /**
     * 获取所有菜单项
     * @return --Array 菜单列表
     * 
    */
    getAllMenu() {
        var _this15 = this;

        return _asyncToGenerator(function* () {
            try {
                return _this15.menuModel.findAll();
            } catch (err) {
                return _this15.exceptionService.handleError(err);
            }
        })();
    }

    /************角色菜单 end************* */
};